var ARTICLE_TYPE = {
    FAQ:           1,
    ARTICLE:       2,
    PRESS_RELEASE: 3
};

var PREVIEW_PARAM = {
    1: 'faq',
    2: '',
    3: 'press_release'
};

var FILE_BROWSER = {
    URL: '/admin/media_popup.html',
    WIDTH: 836,
    HEIGHT: 600
};

var g_options = {
    mode: "exact",
    language: "en",
    plugins: "safari,spellchecker,table,searchreplace,print,paste,pasteimage,fullscreen,advimage,media,popuplink",
    theme: "advanced",
    theme_advanced_toolbar_location: "top",
    theme_advanced_toolbar_align: "left",
    theme_advanced_path_location: "bottom",
    forced_root_block : false,
    force_br_newlines : true,
    force_p_newlines : false,
    debug: false,
    apply_source_formatting : true,
    fullpage_default_doctype: "",
    fullpage_default_title: "",
    fullpage_default_font_size: "12px",
    fullpage_default_font_family: "Arial, sans-serif",
    content_css: '/css/style.css,/css/admin/articles.css',
    relative_urls: false,
    convert_urls: false,
    entity_encoding: "raw"
};

var g_optionsMain = {
    spellchecker_rpc_url: '/js/tinymce/plugins/spellchecker/rpc.php',
    elements: "content",
    auto_focus: "content",
    theme_advanced_buttons1: "print,code,|,undo,redo,|,cut,copy,paste,pastetext,pasteword,|,search,replace,|,cleanup,removeformat,|,fullscreen,|,spellchecker",
    theme_advanced_buttons2: "link,unlink,anchor,image,media,popuplink,|,tablecontrols",
    theme_advanced_buttons3: "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,outdent,indent,|,forecolor,backcolor,sub,sup,|,charmap,emotions",
    theme_advanced_buttons4: "styleselect,fontselect,fontsizeselect,formatselect",
    extended_valid_elements: "img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name|style]",
    pasteimage_upload_url: '/upload_image.php?act=add&fromApplet=1',
    pasteimage_upload_file_param_name: "attach",
    width: "680",
    height: "500",
    file_browser_callback: "openFileBrowser",
    media_types: 'flash=swf',
    popuplink_class: 'fancybox-link',
    onchange_callback: "tinyMCEChangeHandler"
};

var g_optionsBrief = {
    elements: 'brief_descr',
    auto_focus: 'brief_descr',
    theme_advanced_buttons1: "code,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,link,unlink,anchor",
    theme_advanced_buttons2: "styleselect,fontselect,fontsizeselect,formatselect",
    extended_valid_elements: "img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name|style]",
    width: "680",
    height: "90",
    onchange_callback: "tinyMCEChangeHandler"
};

var g_optionsGZ = {
    plugins: "safari,spellchecker,table,searchreplace,print,paste,fullscreen",
    theme: "advanced",
    theme_advanced_toolbar_location: "top",
    theme_advanced_toolbar_align: "left",
    theme_advanced_path_location: "bottom",
    theme_advanced_buttons1: "print,code,|,undo,redo,|,cut,copy,paste,pastetext,pasteword,|,search,replace,|,cleanup,removeformat,|,fullscreen,|,spellchecker",
    theme_advanced_buttons2: "bullist,numlist,|,outdent,indent,|,link,unlink,anchor,image,|,tablecontrols",
    theme_advanced_buttons3: "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,forecolor,backcolor,sub,sup,|,charmap,emotions",
    theme_advanced_buttons4: "styleselect,fontselect,fontsizeselect,formatselect",
    languages : 'en',
    disk_cache : true,
    debug : false
};

var editorId = 'content';

tinyMCEPreInit = {base : '/js/tinymce', suffix : ""};

$(document).ready(function(){
    tinyMCE_GZ.init(g_optionsGZ);
    tinyMCE.init();

    tinyMCE.settings = $.extend({}, g_options, g_optionsBrief);
    tinyMCE.execCommand('mceAddControl', true, 'brief_descr');
    tinyMCE.settings = $.extend({}, g_options, g_optionsMain);
    tinyMCE.execCommand('mceAddControl', true, "content");

    $(".common_errors_container").css({'width': (($(".form_container").outerWidth() - 2) + "px")});


    /* fix footer position */
    $("div.footer_container div.footer").css({'marginBottom': "-21px"});

    if ( $.trim( $(".error_message_container").html() ) == "" )
    {
        $(".error_message_container").html("<div class='global_error_field'></div>");
        $(".error_message_container .global_error_field").hide();
    }

    $('#type').change(function () {
        toggleFields($(this).val());
    }).trigger('change');

    jQuery.validator.messages.equalTo = Messages.Admin.TitleRequired;

    var validateParams = {
        rules:
        {
            type: "required",
            language: "required",
            title: "required",
            slug: "required",
            category: {
                required: function() {
                    return $('#type').val() == ARTICLE_TYPE.FAQ;
                }
            },
            excerpt: {
                required: function() {
                    return $('#type').val() != ARTICLE_TYPE.FAQ;
                }
            },
            content: "required",
            publish_date: {
                required: function() {
                    return $('#published').attr('checked');
                }
            }
        },

        messages:
        {
            type:          "<strong>Type: </strong>" + Messages.Admin.TypeRequired,
            language:      "<strong>Language: </strong>" + Messages.Admin.LanguageRequired,
            title:         "<strong>Title: </strong>" + Messages.Admin.TitleRequired,
            slug:          "<strong>URL: </strong>" + Messages.Admin.UrlRequired,
            category:      "<strong>Category: </strong>" + Messages.Admin.CategoryRequired,
            excerpt:       "<strong>Brief Description: </strong>" + Messages.Admin.BriefDescrRequired,
            content:       "<strong>Content: </strong>" + Messages.Admin.ContentRequired,
            publish_date:  "<strong>Publishing Date: </strong>" + Messages.Admin.PublishDateRequired
        }
    };

    var adminArticleFormValidatorSettings = generateSettings( validateParams );

    $('#publish_date').datepicker({
        dateFormat: 'yy-mm-dd',
        changeMonth: true,
        changeYear: true,
        constrainInput: true
    });

    $('#sendButton').click( function() {
        // required to update textareas content
        tinyMCE.triggerSave();
    } );

    $('#article_form_info').validate( adminArticleFormValidatorSettings );

    $('#previewButton').click(function(e){
        e.stopPropagation();
        var width = 800;
        var height = 800;
        var top  = Math.ceil( (screen.height - height) / 2 );
        var left = Math.ceil( (screen.width - width) / 2 );

        var href = $(this).attr('href');
        var param = PREVIEW_PARAM[ $('#type').val() ];
        if (param)
        {
            href += '?' + param;
        }
        var options = 'width=' + width
        + ',height=' + height
        + ',top=' + top
        + ',left=' + left
        + ',scrollbars=yes,menubar=no,toolbar=no,location=no';
        var newWin = window.open(href, 'Article Preview', options);
        newWin.focus();
        return false;
    });

    $('#language').change( handleLanguageChange ).trigger('change');
});

function toggleFields(type)
{
   $('#category_row').show();
}

function handleLanguageChange()
{
    // disabled, because only one language is used
    /*
    var categorySelect = $('#category');
    categorySelect.empty();
    categorySelect.attr('disabled', 'disabled');
    categorySelect.html("<option>Loading...</option>");
    var params = {'language': $(this).val()};
    $.get('categories_ajax.php', params, function(data) {
          categorySelect.empty();
          categorySelect.removeAttr('disabled');
          populateSelect(categorySelect, data, $('input[name="sel_category"]').val())
        }, 'json');*/    
}

function populateSelect(select, data, selected)
{
    var option;
    var i = 0;
    for (var id in data)
    {
        option = document.createElement("OPTION");
        option.value = id;
        option.text = data[id];
        if (id == selected)
        {
            option.selected = true;
        }
        select.get(0).options[i] = option;
        i++;
    }
}

function getEditorContent()
{
    return tinyMCE.getInstanceById("content").getContent();
}

function getArticleTitle()
{
    return $('#article_title').val();
}

function openFileBrowser(field_name, url, type, win)
{
    var crmUrl = FILE_BROWSER.URL;    // script URL - use an absolute path!
    if (crmUrl.indexOf("?") < 0)
    {
        //add the type as the only query parameter
        crmUrl = crmUrl + "?type=" + type;
    }
    else
    {
        //add the type as an additional query parameter
        // (PHP session ID is now included if there is one at all)
        crmUrl = crmUrl + "&type=" + type;
    }

    tinyMCE.activeEditor.windowManager.open(
        {
            file : crmUrl,
            title : 'File Browser',
            width : FILE_BROWSER.WIDTH,  // Your dimensions may differ - toy around with them!
            height : FILE_BROWSER.HEIGHT,
            resizable : "yes",
            scrollbars: "yes",
            inline : "false",  // This parameter only has an effect if you use the inlinepopups plugin!
            close_previous : "no"
        },
        {
            window : win,
            input : field_name
        }
    );

    return false;
}

function tinyMCEChangeHandler(inst)
{
    tinyMCE.triggerSave();
    $('#article_form_info').validate().element('#' + inst.id);
}
